package cn.flying.cloud.auth.security.handler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

import cn.flying.cloud.auth.security.exception.TokenExpiredException;
import cn.flying.cloud.auth.security.exception.TokenIllegalException;
import cn.flying.cloud.base.common.enums.RtCodeEnum;
import cn.flying.cloud.base.common.vo.Rt;

/**
 * 未登录访问（匿名用户访问）无权限资源时的异常处理器
 *
 * @author: admin
 * @date: 2023年05月25日 19:29
 * @version: 1.0
 */
@Component
public class CustomUnauthorizedEntryPointHandler implements AuthenticationEntryPoint {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * @param request   that resulted in an <code>AuthenticationException</code>
     * @param response  so that the user agent can begin authentication
     * @param exception that caused the invocation
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.error("认证异常，匿名用户访问未授权资源", exception);

        RtCodeEnum codeEnum = RtCodeEnum.R10015;
        if (exception instanceof TokenExpiredException) {
            codeEnum = RtCodeEnum.R10005;
        } else if (exception instanceof TokenIllegalException) {
            codeEnum = RtCodeEnum.R10005;
        }

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(Rt.error(codeEnum), JSONWriter.Feature.WriteMapNullValue));
        out.flush();
        out.close();
    }
}
